package com.lottery.ruok.lottrey.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.applozic.mobicomkit.uiwidgets.conversation.messageUtils.ChatRecordUtils;
import com.applozic.mobicomkit.uiwidgets.conversation.messageUtils.SearchRecordUtils;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.ActivitiesCenterActivity;
import com.lottery.ruok.lottrey.activity.ActivitiesViewpagerActivity;
import com.lottery.ruok.lottrey.activity.ChargeActivity;
import com.lottery.ruok.lottrey.activity.LiuhecaiPrizeActivity;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.activity.MainActivity;
import com.lottery.ruok.lottrey.activity.WebViewActivity;
import com.lottery.ruok.lottrey.adapter.ActivitiesViewPageAdapter;
import com.lottery.ruok.lottrey.adapter.GlideImageLoader;
import com.lottery.ruok.lottrey.adapter.HomeCPAdapter;
import com.lottery.ruok.lottrey.adapter.NoticePageAdapter;
import com.lottery.ruok.lottrey.adapter.VerticalSwitchViewAdapter;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.ActivitiesCenterActivityObj;
import com.lottery.ruok.lottrey.eventbusObject.GotoBuyPage;
import com.lottery.ruok.lottrey.eventbusObject.LogOut;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.RefreshRoomStatus;
import com.lottery.ruok.lottrey.eventbusObject.ReloadLotteryEvent;
import com.lottery.ruok.lottrey.interfaces.BaseAnimationListener;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.ActivityListRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetHasSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetLotteryNoticeRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetNoticeMsgsRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWholeCategoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWinningRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetActivitiesKeysResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetHasSMSResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLotteryNoticeResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWinningResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.NoticeMsgsResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.ReceiveRewardResponse;
import com.lottery.ruok.lottrey.ui.ResizableImageView;
import com.lottery.ruok.lottrey.ui.component.HomeCPGroupView;
import com.lottery.ruok.lottrey.ui.widget.ActivitiesView;
import com.lottery.ruok.lottrey.ui.widget.MarqueeTextView;
import com.lottery.ruok.lottrey.ui.widget.SuperViewPager;
import com.lottery.ruok.lottrey.ui.widget.VerticalSwitchView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.RandomWinnerUtils;
import com.lottery.ruok.lottrey.utils.StringUtils;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import utils.Utils;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;

public class HomeMainFragment extends BaseMainFragment {
    private static final int ACTIVITIES_AWAIT = 1;
    private static final int ACTIVITIES_PROCESS = 2;
    private static final int ACTIVITIES_OVERDUE = 3;
    private static final int ACTIVITIES_STOAP = 4;

    @BindView(R.id.charge_layout)
    LinearLayout chargeLayout;
    @BindView(R.id.discounts)
    LinearLayout discounts;
    @BindView(R.id.horizontal_list)
    RecyclerView horizontalList;
//    @BindView(R.id.scrollView)
//    NoTouchListView scrollView;
//    @BindView(R.id.scrollView1)
//    NoTouchListView scrollView1;
    @BindView(R.id.verticle_switchView)
    VerticalSwitchView switchView;
    @BindView(R.id.verticle_switchView2)
    VerticalSwitchView switchView2;
    @BindView(R.id.online_consult)
    View online_consult;
    @BindView(R.id.scrolls)
    NestedScrollView nestedScrollView;
    @BindView(R.id.login_btn)
    TextView login_btn;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.login_layout)
    View login_layout;
    @BindView(R.id.tv_recommended_download)
    TextView tv_recommended_download;
    @BindView(R.id.my_recycler_view)
    RecyclerView mHotRecyclerView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.event_center)
    LinearLayout eventCenter;
    @BindView(R.id.indicator_title)
    TextView indicatorTitle;
    @BindView(R.id.tv_marquee)
    MarqueeTextView mTvMarquee;
    @BindView(R.id.notice_layout)
    LinearLayout mNoticeLayout;
    @BindView(R.id.notice_line)
    View mNoticeLine;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.event_center_block)
    RelativeLayout eventCenterBlock;
    @BindView(R.id.activity)
    ResizableImageView activity;
    @BindView(R.id.activities_page)
    SuperViewPager activitiesPage;
    @BindView(R.id.btn_last)
    ImageButton btnLast;
    @BindView(R.id.btn_next)
    ImageButton btnNext;
    @BindView(R.id.huodongzhongxin)
    TextView huodongzhongxin;
    @BindView(R.id.ll_prize1)
    LinearLayout ll_prize1;
    @BindView(R.id.ll_prize2)
    LinearLayout ll_prize2;
    private ActivityListResponse mActivityListResponse;
    private NoticePageAdapter mAdapter_horizontal;
    private int mCurrentPosition = 0;
    private boolean isListTouch = false;
    private long autoScrollTime = 0;
    private int mIndex = 0;
    private boolean startWinDown = false;
    private boolean startCountDown2 = false;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private HomeCPAdapter mHotAdapter;
    private volatile int mPageCurrentItem = 0;
    private long page_autoScrollTime = System.currentTimeMillis();
    private boolean isJoined;
    private ArrayList<ActivityListResponse.ListBean> joninedActvities;
    private GetActivitiesKeysResponse mActivitiesKeysResponse;
    private boolean mIsOnPause = false;
    private GetHasSMSResponse smsResponse;
    private VerticalSwitchViewAdapter switchAdapter;
    private List<GetWinningResponse> winners;
    private String type;
    private static final String MODE_1 = "1";
    private static final String MODE_2 = "2";
    private static final String MODE_3 = "3";

    private CountDownManager.CountDownModel countDownModel = new CountDownManager.CountDownModel() {
        @Override
        public void onExecute() {
            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        if (startWinDown) {
//                            scrollView.setSelection(Integer.MAX_VALUE / 2 + 1 - 3 * mIndex);
//                            scrollView1.setSelection(Integer.MAX_VALUE / 2 + 1 - 3 * mIndex);
                            mIndex++;
                            if(mIndex % 2 == 0){
                                if(!TextUtils.isEmpty(type) && type.equals(MODE_2)) {
                                    switchView.showNext();
                                    switchView.recodeSwtichIndex();
                                }
                                if(!TextUtils.isEmpty(type) && type.equals(MODE_3)) {
                                    switchView2.showNext();
                                    switchView2.recodeSwtichIndex();
                                }
                            }
//                        }
                        if (startCountDown2) {
                            for (GetLotteryNoticeResponse getLotteryNoticeResponse : mAdapter_horizontal.getDatas()) {
                                getLotteryNoticeResponse.pasttime++;
                                if (getLotteryNoticeResponse.pasttime > getLotteryNoticeResponse.getTime()) {
                                    getLotteryNoticeResponse.pasttime = 0;
                                    getLotteryNoticeResponse.setTime(getLotteryNoticeResponse.getInterval());
                                }
                            }

                            if (!horizontalList.isComputingLayout() && RecyclerView.SCROLL_STATE_IDLE == horizontalList.getScrollState()) {
                                mAdapter_horizontal.notifyDataSetChanged();
                            }

                            if (System.currentTimeMillis() - autoScrollTime > 6000) {
                                autoScrollTime = System.currentTimeMillis();
                                if (!isListTouch) {
                                    if (mCurrentPosition + 1 < mAdapter_horizontal.getDatas().size()) {
                                        horizontalList.smoothScrollToPosition(mCurrentPosition + 1);
                                        mCurrentPosition++;
                                    } else {
                                        mCurrentPosition = 0;
                                        horizontalList.scrollToPosition(mCurrentPosition);
                                    }
                                }

                            }
                            if (!mIsOnPause && joninedActvities != null && joninedActvities.size() > 1) {
                                if (System.currentTimeMillis() - page_autoScrollTime > 6000) {
                                    mPageCurrentItem++;
                                    if (mPageCurrentItem >= joninedActvities.size()) {
                                        mPageCurrentItem = 0;
                                    }
                                    activitiesPage.setCurrentItem(mPageCurrentItem);
                                }
                            }
                        }
                    }

                });
            }
        }
    };

    private void countDown() {
        CountDownManager.asInstance().register(countDownModel);
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_fragment, container, false);
        ButterKnife.bind(this, view);
        initView();
        isPrepared = true;
        initSwitchData();
        lazyLoad();
        load();
        countDown();
        return view;
    }

    private void initSwitchData() {
        winners = RandomWinnerUtils.getWinners(6);
        switchAdapter = new VerticalSwitchViewAdapter(winners);
        switchView.setAdapter(switchAdapter);
        switchView.getInAnimation().setAnimationListener(new BaseAnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                switchView.refreshData(RandomWinnerUtils.getWinners(3));
            }
        });
        switchView2.setAdapter(switchAdapter);
        switchView2.getInAnimation().setAnimationListener(new BaseAnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                switchView2.refreshData(RandomWinnerUtils.getWinners(3));
            }
        });
    }

    private void initView() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                load();
                EventBus.getDefault().post(new RefreshRoomStatus());
            }
        });
        mHotAdapter = new HomeCPAdapter(getActivity());
        mHotAdapter.setOnMoreBuyLotteryClickListener(new HomeCPGroupView.MoreBuyLotteryClickListener() {
            @Override
            public void onClick(GetWholeCategoryResponse data) {
                //跳转到buyfragment
                EventBus.getDefault().post(new GotoBuyPage(data.getCode()));
            }
        });
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mLayoutManager.setAutoMeasureEnabled(true);
        mHotRecyclerView.setLayoutManager(mLayoutManager);
        mHotRecyclerView.setHasFixedSize(true);//如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mHotRecyclerView.setNestedScrollingEnabled(false);
        mHotRecyclerView.setAdapter(mHotAdapter);


        if (UserInfo.getToken().equals("")) {
            setUnLoginState();
        } else {
            setLoginState();
        }
    }

    private void load() {
        getPrizeSwitch();
        getSlideShow();
//        getWeb();
        getList();
        getNotices();
        getHotCPData();
        loadActivities();
    }

    private void getPrizeSwitch() {
        RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("enable_prize")
                .compose(RxHelper.<GetHasSMSResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetHasSMSResponse>(getContext()) {
                    @Override
                    protected void _onNext(GetHasSMSResponse getHasSMSResponse) {
                        if (getHasSMSResponse != null && getHasSMSResponse.getValue() != null && !getHasSMSResponse.getValue().toString().equals("null")) {
                            //
                            if ("enable_prize".equals(getHasSMSResponse.getKey()))
                                type = getHasSMSResponse.getValue().getAsString();
                                switch (type) {
                                    case MODE_1:
                                        ll_prize1.setVisibility(View.GONE);
                                        ll_prize2.setVisibility(View.GONE);
                                        break;
                                    case MODE_2:
                                        ll_prize1.setVisibility(View.VISIBLE);
                                        ll_prize2.setVisibility(View.GONE);
                                        break;
                                    case MODE_3:
                                        ll_prize1.setVisibility(View.GONE);
                                        ll_prize2.setVisibility(View.VISIBLE);
                                        break;
                                }

                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void loadActivities() {
        RetrofitBase.getRetrofit().create(ActivityListRequest.class)
                .getResult(UserInfo.getToken(), null, null)
                .compose(RxHelper.<ActivityListResponse>handleResult())
                .subscribe(new RxSubscribe<ActivityListResponse>(getActivity()) {
                    @Override
                    protected void _onNext(ActivityListResponse activityListResponse) {
                        mActivityListResponse = activityListResponse;
                        EventBus.getDefault().post(new ActivitiesCenterActivityObj(activityListResponse));
                        setActivitiesList();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        eventCenterBlock.setVisibility(View.GONE);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        CountDownManager.asInstance().unRegister(countDownModel);
        EventBus.getDefault().unregister(this);
        super.onDetach();

    }

    /**
     * 登录
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        setLoginState();
        ChatRecordUtils.init();
        SearchRecordUtils.init();
    }

    /**
     * 登出
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LogOut event) {
        nestedScrollView.fullScroll(ScrollView.FOCUS_UP);
        setUnLoginState();

    }

    /**
     * 刷新活动List
     *
     * @param activityListResponse
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ActivityListResponse activityListResponse) {
       loadActivities();
    }

    /**
     * 领取奖励后刷新活动
     *
     * @param receiveRewardRequest
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ReceiveRewardResponse receiveRewardRequest) {
        loadActivities();
    }

    /**
     * 活动开关
     *
     * @param activitiesKeysResponse
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetActivitiesKeysResponse activitiesKeysResponse) {
        mActivitiesKeysResponse = activitiesKeysResponse;
        if (mActivitiesKeysResponse != null) {
            if (activitiesKeysResponse.getEnable_activities_icon() == 0) {
                eventCenter.setVisibility(View.GONE);
            } else {
                if ("".equals(UserInfo.getToken())) {
                    eventCenter.setVisibility(View.GONE);
                } else {
                    eventCenter.setVisibility(View.VISIBLE);
                }
            }
            if (mActivitiesKeysResponse.getEnable_activities_panel() == 0) {
                eventCenterBlock.setVisibility(View.GONE);
            } else {
                eventCenterBlock.setVisibility(View.VISIBLE);
            }
        }
    }

    private void getWeb() {
        try {
            RetrofitBase.getRetrofit().create(GetWinningRequest.class).getResult()
                    .compose(RxHelper.<ArrayList<GetWinningResponse>>handleResult())
                    .subscribe(new RxSubscribe<ArrayList<GetWinningResponse>>(getActivity()) {
                        @Override
                        protected void _onNext(ArrayList<GetWinningResponse> getWinningResponses) {
//                            scrollView.setAdapter(new WinningAdapter(getWinningResponses, getActivity()));
//                            scrollView.setSelection(Integer.MAX_VALUE / 2 + 1);
//                            scrollView1.setAdapter(new WinningAdapter(getWinningResponses, getActivity()));
//                            scrollView1.setSelection(Integer.MAX_VALUE / 2 + 1);
                            startWinDown = true;
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setActivitiesList() {
        isJoined = false;
        joninedActvities = new ArrayList<>();
        for (ActivityListResponse.ListBean listBean : mActivityListResponse.getList()) {
            /**
             * 去除暂停，过期，待发布的任务,已完成
             */
            ArrayList<ActivityListResponse.ListBean.MissionsBean> missions = listBean.getMissions();
            for (ActivityListResponse.ListBean.MissionsBean mission : missions) {
                if (mission.getStatus() == 3) listBean.setStatus(2);
            }
            if (listBean.getStatus() == ACTIVITIES_PROCESS) {//
                isJoined = true;
                joninedActvities.add(listBean);
            }
        }
        indicatorTitle.setText("活动" + 1 + "/共参与进行中" + (joninedActvities.size()) + "个活动");
        List<View> views = new ArrayList<>();
        if (!isJoined || Utils.isEmpty(UserInfo.getToken())) {//未登录或者为参加任何活动就只展示第一个活动
            //当前没有参加的活动
            btnLast.setVisibility(View.INVISIBLE);
            btnNext.setVisibility(View.INVISIBLE);
            indicatorTitle.setVisibility(View.INVISIBLE);
            ActivitiesView activitiesView = new ActivitiesView(getActivity());
            if (mActivityListResponse.getList() != null && mActivityListResponse.getList().size() > 0) { //有任务
                activitiesView.setData(mActivityListResponse.getList().get(0));
                activitiesView.setOnActivitiesCardClickListener(new ActivitiesView.OnActivitiesCardClickListener() {
                    @Override
                    public void onClick() {
                        Intent intent = new Intent(HomeMainFragment.this.getActivity(), ActivitiesViewpagerActivity.class);
                        ArrayList<ActivityListResponse.ListBean> data = new ArrayList<>();
                        data.add(mActivityListResponse.getList().get(0));
                        intent.putExtra("data", data);
                        intent.putExtra("position", 0);
                        HomeMainFragment.this.getActivity().startActivity(intent);
                    }
                });
            } else {//无任务
//                activitiesView.setData(null);
                eventCenterBlock.setVisibility(View.GONE);
            }

            views.add(activitiesView);
            huodongzhongxin.setVisibility(View.VISIBLE);
            activitiesView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转到活动中心
                    Intent intent1 = new Intent(getActivity(), ActivitiesCenterActivity.class);
                    intent1.putExtra("activities_response", mActivityListResponse);
                    startActivity(intent1);
                }
            });
        } else {
            //有参加的活动
            btnLast.setVisibility(View.VISIBLE);
            btnNext.setVisibility(View.VISIBLE);
            indicatorTitle.setVisibility(View.VISIBLE);
            huodongzhongxin.setVisibility(View.INVISIBLE);
            for (ActivityListResponse.ListBean listBean : joninedActvities) {
                ActivitiesView activitiesView = new ActivitiesView(getActivity());
                activitiesView.setData(listBean);
                views.add(activitiesView);
                activitiesView.setOnActivitiesCardClickListener(new ActivitiesView.OnActivitiesCardClickListener() {
                    @Override
                    public void onClick() {
                        Intent intent = new Intent(HomeMainFragment.this.getActivity(), ActivitiesViewpagerActivity.class);
                        intent.putExtra("data", joninedActvities);
                        intent.putExtra("position", activitiesPage.getCurrentItem());
                        HomeMainFragment.this.getActivity().startActivity(intent);
                    }
                });
            }
        }
        activitiesPage.setAdapter(new ActivitiesViewPageAdapter(views));
        activitiesPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicatorTitle.setText("活动" + (position + 1) + "/共参与进行中" + (joninedActvities.size()) + "个活动");
                page_autoScrollTime = System.currentTimeMillis();
                mPageCurrentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        activitiesPage.setOnTouchListener(new SuperViewPager.OnTouchListener() {
            @Override
            public void onTouch(int state) {
                if (state == SuperViewPager.STATE_DOWN) {
                    mIsOnPause = true;
                } else if (state == SuperViewPager.STATE_UP) {
                    mIsOnPause = false;
                }
            }
        });
    }
    //公告
    private void getNotices() {
        RetrofitBase.getRetrofit().create(GetNoticeMsgsRequest.class).getResult()
                .compose(RxHelper.<ArrayList<NoticeMsgsResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<NoticeMsgsResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<NoticeMsgsResponse> noticeMsgsResponses) {
                        if(noticeMsgsResponses.size() <= 0){
                            mNoticeLayout.setVisibility(View.GONE);
                            mNoticeLine.setVisibility(View.GONE);
                            return;
                        }
                        mNoticeLine.setVisibility(View.VISIBLE);
                        mNoticeLayout.setVisibility(View.VISIBLE);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < noticeMsgsResponses.size(); i++) {
                            NoticeMsgsResponse msgsResponse = noticeMsgsResponses.get(i);
                            stringBuilder.append(msgsResponse.getContent());
                            if (i != noticeMsgsResponses.size() - 1) {
                                stringBuilder.append("   ");
                            }
                        }
                        mTvMarquee.setText(StringUtils.delHTMLTag(stringBuilder.toString()));
                        mTvMarquee.setSelected(true);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void getList() {
        try {
            RetrofitBase.getRetrofit().create(GetLotteryNoticeRequest.class).getResult(1, "hot_category", null)
                    .compose(RxHelper.<ArrayList<GetLotteryNoticeResponse>>handleResult())
                    .subscribe(new RxSubscribe<ArrayList<GetLotteryNoticeResponse>>(getActivity()) {
                        @Override
                        protected void _onNext(final ArrayList<GetLotteryNoticeResponse> getLotteryNoticeResponses) {
                            if (getLotteryNoticeResponses != null && getLotteryNoticeResponses.size() > 0) {
                                getLotteryNoticeResponses.get(0).isLeft = true;
                                getLotteryNoticeResponses.get(getLotteryNoticeResponses.size() - 1).isRight = true;
                                final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
                                if (mAdapter_horizontal == null) {
                                    mAdapter_horizontal = new NoticePageAdapter(getLotteryNoticeResponses, getContext(), R.layout.item_home_notice_pager, true);
                                    horizontalList.setHasFixedSize(true);
                                    horizontalList.setLayoutManager(layoutManager);
                                    horizontalList.setAdapter(mAdapter_horizontal);

                                    LinearSnapHelper mGallerySnapHelper = new LinearSnapHelper();
                                    mGallerySnapHelper.attachToRecyclerView(horizontalList);
                                } else {
                                    mAdapter_horizontal.setDatas(getLotteryNoticeResponses);
                                    mAdapter_horizontal.notifyDataSetChanged();
                                }
                                mAdapter_horizontal.setOnItemClickListener(new NoticePageAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View view, int position) {
                                        if (position < getLotteryNoticeResponses.size()) {
                                            gotoLotteryDetailActivity(getLotteryNoticeResponses.get(position).getCode(), getLotteryNoticeResponses.get(position).getItem_class());
                                        }
                                    }
                                });
                                horizontalList.addOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);

                                        if (newState == SCROLL_STATE_IDLE) {
                                            int position = layoutManager.findFirstCompletelyVisibleItemPosition();
                                            if (position != -1) {
                                                mCurrentPosition = position;
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                    }
                                });
                                horizontalList.setOnTouchListener(new View.OnTouchListener() {
                                    @Override
                                    public boolean onTouch(View v, MotionEvent ev) {
                                        autoScrollTime = System.currentTimeMillis();
                                        if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_MOVE) {
                                            isListTouch = true;
                                        } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
                                            isListTouch = false;
                                        }
                                        return false;
                                    }
                                });

                                startCountDown2 = true;

                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);

                            swipeRefreshLayout.setRefreshing(false);
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getSlideShow() {
        try {
            RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("mobile_gallery")
                    .compose(RxHelper.<GetHasSMSResponse>handleResult())
                    .subscribe(new RxSubscribe<GetHasSMSResponse>(getActivity()) {
                        @Override
                        protected void _onNext(final GetHasSMSResponse getNewsResponse) {
                            if (getActivity() != null) {
                                if (getActivity().isDestroyed()) {
                                    return;
                                }
                            }
                            if (getActivity() != null) {
                                banner.setImageLoader(new GlideImageLoader());
                                ArrayList<String> images = new ArrayList();
                                if (getNewsResponse != null && getNewsResponse.getValue() != null) {
                                    for (int i = 0; i < getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().size(); i++) {
                                        if (getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(i).getAsJsonObject().get("image") != null) {
                                            images.add(getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(i).getAsJsonObject().get("image").getAsString());
                                        }
                                    }
                                    int time_interval = 0;
                                    try {
                                        time_interval = getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(0).getAsJsonObject().get("time_interval").getAsInt();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    if (time_interval == 0) {
                                        time_interval = 6000;
                                    } else {
                                        time_interval = time_interval * 1000;
                                    }
                                    banner.setImages(images).setImageLoader(new GlideImageLoader()).setDelayTime(time_interval).start();

                                    banner.setOnBannerListener(new OnBannerListener() {
                                        @Override
                                        public void OnBannerClick(int position) {
                                            if (getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link") != null && getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link").getAsString() != null) {
                                                if (getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link").getAsString().contains("/#discount")) {
                                                    WebViewActivity.startActivity(getActivity(), "优惠活动", getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link").getAsString());
                                                } else if (getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link").getAsString().contains("lobby")) {
                                                    ((MainActivity) getActivity()).viewPager.setCurrentItem(1);
                                                } else if (getNewsResponse.getValue().getAsJsonObject().get("list").getAsJsonArray().get(position).getAsJsonObject().get("link").getAsString().contains("xglhc")) {
                                                    Intent intent = new Intent(getActivity(), LiuhecaiPrizeActivity.class);
                                                    intent.putExtra("code", "xglhc");
                                                    startActivity(intent);
                                                }
                                            }

                                        }
                                    });
                                }
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setUnLoginState() {
        login_btn.setVisibility(View.VISIBLE);
        login_layout.setVisibility(View.VISIBLE);
        eventCenter.setVisibility(View.GONE);
        loadActivities();
    }

    private void setLoginState() {
        login_btn.setVisibility(View.GONE);
        login_layout.setVisibility(View.GONE);
        if (mActivitiesKeysResponse != null) {
            if (mActivitiesKeysResponse.getEnable_activities_icon() == 0) {
                eventCenter.setVisibility(View.GONE);
            } else {
                eventCenter.setVisibility(View.VISIBLE);
                activitiesPage.setOffscreenPageLimit(3);
                loadActivities();
            }
        }
    }

    @OnClick({R.id.charge_layout, R.id.discounts, R.id.demo, R.id.login_btn, R.id.online_consult, R.id.login_layout, R.id.tv_recommended_download, R.id.activity, R.id.tv_more, R.id.event_center, R.id.btn_last, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_recommended_download://推荐下载
                WebViewActivity.startActivity(getActivity(), "", UserInfo.getQuickDomain() + "promotion?token=" + UserInfo.getToken());
                break;
            case R.id.activity:
                Utils.showToast("即将上架敬请期待！");
                break;
            case R.id.charge_layout:
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent1 = new Intent(getActivity(), ChargeActivity.class);
                        startActivity(intent1);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.discounts:
                WebViewActivity.startActivity(getActivity(), "优惠活动", "");


                break;
            case R.id.demo://由试玩改成提现
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        withdrawMoney();
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.login_btn:
            case R.id.login_layout:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_home_login");

                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                break;
            case R.id.online_consult:
                if (StringUtils.isNotEmpty(Common.service_url)) {
                    Utils.openBrowser(Common.service_url, getActivity());
                } else {
                    Utils.showToast(Common.NO_SERVICE);
                }

                break;
            case R.id.tv_more:
                Intent intent1 = new Intent(getActivity(), ActivitiesCenterActivity.class);
                intent1.putExtra("activities_response", mActivityListResponse);
                startActivity(intent1);
                break;
            case R.id.event_center:
                Intent intent2 = new Intent(getActivity(), ActivitiesCenterActivity.class);
                intent2.putExtra("activities_response", mActivityListResponse);
                startActivity(intent2);
                break;
            case R.id.btn_last:
                mPageCurrentItem--;
                if (mPageCurrentItem <= -1) {
                    mPageCurrentItem = joninedActvities.size() - 1;
                }
                activitiesPage.setCurrentItem(mPageCurrentItem);

                break;
            case R.id.btn_next:
                mPageCurrentItem++;
                if (mPageCurrentItem >= joninedActvities.size()) {
                    mPageCurrentItem = 0;
                }
                activitiesPage.setCurrentItem(mPageCurrentItem);
                break;
        }
    }


    public void getHotCPData() {
        // 首页有跳转到购彩大厅的需求，需提前加载
        EventBus.getDefault().post(new ReloadLotteryEvent());
        try {
            RetrofitBase.getRetrofit().create(GetWholeCategoryRequest.class).getResult(UserInfo.getToken(), 0, 0)
                    .compose(RxHelper.<ArrayList<GetWholeCategoryResponse>>handleResult())
                    .subscribe(new RxSubscribe<ArrayList<GetWholeCategoryResponse>>(getActivity()) {
                        @Override
                        protected void _onNext(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses) {
                            handlerWinnerCategories(getWholeCategoryResponses);
                            handlerCategories(getWholeCategoryResponses);
                            if (mHotAdapter != null) {
                                mHotAdapter.setList(getWholeCategoryResponses);
                                UserInfo.setDefaultLottery(getWholeCategoryResponses.get(0).getItems().get(0).getCode());
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlerWinnerCategories(ArrayList<GetWholeCategoryResponse> data){
        List<GetWholeCategoryResponse.ItemsBean> allCategory = null;
        List<GetWholeCategoryResponse.ItemsBean> dpcCategory = null;
        for(GetWholeCategoryResponse categoryResponse : data){
            if(categoryResponse.getName().equals("全部")){
                allCategory = categoryResponse.getItems();
            }
            if(categoryResponse.getName().equals("低频彩")){
                dpcCategory = categoryResponse.getItems();
            }
        }
        boolean isContains;
        for(int i = allCategory.size() - 1; i>=0; i--){
            isContains = false;
            for(int j=0; j < dpcCategory.size(); j++){
                if(allCategory.get(i).getCode().equals(dpcCategory.get(j).getCode())){
                    isContains = true;
                }
            }
            if(isContains){
                allCategory.remove(i);
            }
        }

        String [] newLotters = new String[allCategory.size()];
        for(int i=0; i<allCategory.size(); i++){
            newLotters[i] = allCategory.get(i).getName();
        }

        RandomWinnerUtils.setLottery(newLotters);
    }


    /**
     * 处理数据
     */
    private void handlerCategories(ArrayList<GetWholeCategoryResponse> data) {
        if (data != null) {
            Iterator<GetWholeCategoryResponse> iterator = data.iterator();
            while (iterator.hasNext()) {
                GetWholeCategoryResponse item = iterator.next();
                if ("热门".equals(item.getName()) || "全部".equals(item.getName())) {
                    data.remove(item);
                    continue;
                }
                int size = item.getItems().size();
                if (size % 2 != 0) {
                    item.getItems().remove(size - 1);
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsOnPause = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsOnPause = false;
    }
}